# 定义一个转换函数
import requests
import time


def to_str(value):
    return str(value).strip() if value is not None else ''

def to_int(value):
    return int(value) if value is not None else None

# 定义获取 Access token 方法
def get_access_token():
    params = {
        "grant_type": "client_credential",
        "appid": "wxcc8c807334afbb6d",
        "secret": "6304185f7fc60cc8e67986c85d33124c"
    }
    response = requests.get(url="https://api.weixin.qq.com/cgi-bin/token", params=params)
    print(response.json())


class WeChatTokenManager:
    def __init__(self):
        self.appid = "wxcc8c807334afbb6d"
        self.appsecret = "6304185f7fc60cc8e67986c85d33124c"
        self.token = None
        self.expire_time = 0

    # 获取 token
    def get_token(self):
        # 检查 token 是否过期
        if self.token is None or time.time() > self.expire_time:
            self.refresh_token()
        return self.token

    def refresh_token(self):
        # 调用微信接口获取 token
        url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.appid}&secret={self.appsecret}"
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            self.token = data['access_token']
            # 设置过期时间为当前时间加上有效期（秒）
            self.expire_time = time.time() + data['expires_in']
        else:
            raise Exception(f"Failed to get token: {response.text}")

# 调用微信 API 获取用户信息
def get_user_info(open_id, token):
    url = f"https://api.weixin.qq.com/cgi-bin/user/info?access_token={token}&openid={open_id}&lang=zh_CN"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Failed to get user info: {response.text}")



if __name__ == '__main__':
    # 调用示例
    get_access_token()
   # user_info = get_user_info('user_open_id', '123')
    #print(user_info)